import { defineStore } from 'pinia'
import { computed, ref } from 'vue'
import { Router } from 'vue-router'
import localforage from 'localforage'

// 从外部导入一下router
let router: Router = null
export const setTabStoreRouter = (r: Router) => {
  router = r
}

//
//
//头部标签列表
export const useTabStore = defineStore('tab', () => {
  interface SubApplicationItem {
    id: string
    path: string
    name: string
    description: string
    image: string
  }

  //当前标签id
  const currentTabId = ref<string>('')
  //标签列表
  const tabList = ref<SubApplicationItem[]>([])

  // 初始化本地标签列表
  async function initTabList() {
    const tabMap = new Map<string, SubApplicationItem>(
      await localforage.getItem('tabList')
    )
    tabList.value = tabMap ? Array.from(tabMap.values()) : []
    if (currentTabId.value === '') router.push('/home')

    getAppHistoryPath()
  }

  // 设置标签列表，并缓存到本地
  async function setTagList(list: SubApplicationItem[]) {
    tabList.value = list
    const tabMap = new Map<string, SubApplicationItem>()
    list.forEach((item) => tabMap.set(item.id, { ...item }))
    await localforage.setItem('tabList', tabMap)
  }

  //删除一个标签
  function deleteTabItem(id: string) {
    tabList.value = tabList.value.filter((item) => item.id !== id)
    setTagList(tabList.value)

    if (tabList.value.length === 0) {
      currentTabId.value = ''
      return router.push('/home')
    }
    if (tabList.value.some((item) => item.id === currentTabId.value)) return
    if (currentTabId.value === '') return

    currentTabId.value = tabList.value[0].id
    router.push(tabList.value[0].path)
  }

  // 设置当前标签id
  function setCurrentTabId(id: string) {
    if (currentTabId.value === id) return getAppHistoryPath()

    currentTabId.value = id
    getAppHistoryPath()
  }

  interface AppHistoryPath {
    name: string
    path: string
  }

  // 当前app历史路径
  const currentAppHistoryPath = ref<AppHistoryPath[]>([])

  // 设置当前app历史路径
  async function setAppHistoryPath(
    path: string,
    name: string,
    id: string = null
  ) {
    let appKey = ''
    if (currentTabId.value === '') appKey = 'mainAppHistoryPath'
    else appKey = currentTabId.value + 'AppHistoryPath'
    if (id) appKey = id + 'AppHistoryPath'

    const tab = tabList.value.filter((item) => item.id === currentTabId.value)
    if (tab.length > 0) path = tab[0].path + path

    const history: AppHistoryPath[] = await localforage.getItem(appKey)
    let temp = history ? history : []

    if (temp.length > 0) temp = temp.filter((item) => item.path !== path)
    temp = [{ path, name }, ...temp]
    currentAppHistoryPath.value = temp

    await localforage.setItem(appKey, temp)
  }

  // 获取当前app历史路径
  async function getAppHistoryPath(id: string = null) {
    let appKey = ''
    if (currentTabId.value === '') appKey = 'mainAppHistoryPath'
    else appKey = currentTabId.value + 'AppHistoryPath'
    if (id) appKey = id + 'AppHistoryPath'

    const history: AppHistoryPath[] = await localforage.getItem(appKey)
    currentAppHistoryPath.value = history ? history : []
  }

  // 删除当前app历史路径
  async function deleteAppHistoryPath(path: string, id: string = null) {
    let appKey = ''
    if (currentTabId.value === '') appKey = 'mainAppHistoryPath'
    else appKey = currentTabId.value + 'AppHistoryPath'
    if (id) appKey = id + 'AppHistoryPath'

    const history: AppHistoryPath[] = await localforage.getItem(appKey)
    let temp = history ? history : []

    if (temp.length > 0) temp = temp.filter((item) => item.path !== path)
    else temp = []
    currentAppHistoryPath.value = temp

    await localforage.setItem(appKey, temp)
  }

  return {
    tabList: computed(() => tabList.value),
    currentTabId: computed(() => currentTabId.value),
    setTagList,
    initTabList,
    deleteTabItem,
    setCurrentTabId,
    currentAppHistoryPath: computed(() => currentAppHistoryPath.value),
    setAppHistoryPath,
    getAppHistoryPath,
    deleteAppHistoryPath,
  }
})

//
//
// 路由历史
export const useRouterHistoryStore = defineStore('routerHistory', () => {
  interface PathHistory {
    path: string
    time: string
    count: number
  }

  // 当前路由路径
  const currentPath = ref<PathHistory>(null)
  // 路径记录
  const pathHistory = ref<PathHistory[]>([])

  // 设置路径记录
  async function setPathHistory(path: string) {
    const now = new Date().toLocaleString()
    const item: PathHistory = { path, time: now, count: null }
    currentPath.value = item

    const res = await getPathHistory()
    const temp = res.filter((item) => item.path != path)

    const { 0: currentItem } = res.filter((item) => item.path == path)
    item.count = currentItem?.count + 1 || 1

    const list = [
      item,
      ...temp.map(({ path, time, count }) => {
        return { path, time, count }
      }),
    ]
    await localforage.setItem('pathHistory', list)
  }

  // 获取路径记录
  async function getPathHistory() {
    const pathList: PathHistory[] = await localforage.getItem('pathHistory')
    if (!pathList) return []

    pathHistory.value = pathList.map((item) => item)
    return pathHistory.value
  }

  // 删除一项路径记录
  async function deletePathItem(path: string) {
    const res = await getPathHistory()
    const temp = res.filter((item) => item.path != path)
    const list = temp.map(({ path, time, count }) => {
      return { path, time, count }
    })
    await localforage.setItem('pathHistory', list)
  }

  // 获取访问量最大的路径
  function getMaxCountPath(count: number = 5): PathHistory[] {
    const temp = pathHistory.value.sort((a, b) => b.count - a.count)

    if (temp.length < count) return temp
    return temp.slice(0, count)
  }

  // 获取最新访问的路径
  function getLatestPath(count: number = 5): PathHistory[] {
    const temp = pathHistory.value.sort((a, b) => {
      const bTime = new Date(b.time).getTime()
      const aTime = new Date(a.time).getTime()
      return bTime - aTime
    })

    if (temp.length < count) return temp
    return temp.slice(0, count)
  }

  return {
    currentPath: computed(() => currentPath.value),
    pathHistory: computed(() => pathHistory.value),
    setPathHistory,
    getPathHistory,
    deletePathItem,
    getMaxCountPath,
    getLatestPath,
  }
})
